/*
 * 描述： <描述>
 * 修改人： rain
 * 修改时间： 2016年8月12日
 * 项目： rainhy-config
 */
package com.rainhy.config.manager.xml;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;

import com.rainhy.config.context.ConfigContext;
import com.rainhy.config.manager.BaseConfigPropertiesManager;
import com.rainhy.config.manager.ConfigContextParse;
import com.rainhy.core.exception.RainhyIOException;
import com.rainhy.core.util.XStreamUtils;
import com.thoughtworks.xstream.XStream;

/**
 * XML格式配置属性管理器<br>
 * 
 * @author rain
 * @version [版本号, 2016年8月12日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public abstract class BaseXMLConfigPropertiesManager extends BaseConfigPropertiesManager implements ApplicationContextAware {
    
    /** spring 容器 */
    protected ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    
    @Override
    protected List<ConfigContextParse> loadConfig(ConfigContext configContext, String locations) {
        //加载配置的资源
        Resource[] resources = null;
        try {
            resources = applicationContext.getResources(locations);
        } catch (IOException e) {
            throw new RainhyIOException(e, "加载[资源]异常.location: {}", locations);
        }
        if (ArrayUtils.isEmpty(resources)) {
            return new ArrayList<>();
        }
        List<ConfigContextParse> configContextParseList = new ArrayList<>();
        for (Resource resource : resources) {
            if (!resource.exists() || !resource.isReadable()) {
                logger.warn("[资源]: {} 不存在或者不可能读取.", resource);
                continue;
            }
            
            InputStream in = null;
            try {
                in = resource.getInputStream();
                XStream xStream = XStreamUtils.getXStream(ConfigContextXmlParse.class);
                ConfigContextXmlParse localConfigContextParse = (ConfigContextXmlParse) xStream.fromXML(in);
                configContextParseList.add(localConfigContextParse);
            } catch (IOException e) {
                throw new RainhyIOException(e, "获取XML配置: {} IO流异常. exception: {}", locations, e.toString());
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
        return configContextParseList;
    }
    
}
